package com.jy.appmarket.utils;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.jy.appmarket.model.AppInfoModel;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2014年8月28日
 * @version 1.0
 */

public class PackageUtils {
	public static boolean launchInstall(Context context, String apkPath) {
		if (context == null || apkPath == null) {
			return false;
		}
		try {
			Uri uri = Uri.fromFile(new File(apkPath));
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(uri, "application/vnd.android.package-archive");
			context.startActivity(intent);
			return true;
		} catch (Exception e) {
			// ignore
		}
		return false;
	}

	public static boolean isPackageInstalled(Context context, String pkgName) {
		if (context == null) {
			LogUtil.e("PackageUtils", "context is null");
			return false;
		}
		PackageManager pm = context.getPackageManager();
		try {
			pm.getPackageInfo(pkgName, 0);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean launchPackageFromActivity(Activity activity, String pkgName) {
		try {
			Intent intent = activity.getPackageManager().getLaunchIntentForPackage(pkgName);
			activity.startActivity(intent);
			return true;
		} catch (Exception e) {

		}
		return false;
	}

	public static boolean isSystemApp(Context ctx, String packageName) {

		PackageManager pm = ctx.getPackageManager();
		try {
			PackageInfo pi = pm.getPackageInfo(packageName, 0);
			return (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static List<AppInfoModel> getInstalledUserPackages(Context ctx, boolean getIcon) {
		PackageManager pm = ctx.getPackageManager();
		List<PackageInfo> list = pm.getInstalledPackages(0);
		if (list == null || list.size() == 0) {
			return null;
		}
		List<AppInfoModel> result = new ArrayList<AppInfoModel>();
		for (PackageInfo pi : list) {
			if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
				AppInfoModel app = new AppInfoModel();
				app.setDrawable(pi.applicationInfo.loadIcon(pm));
				app.setName(pi.applicationInfo.loadLabel(pm).toString());
				app.setPackageName(pi.applicationInfo.packageName);
				result.add(app);
			}
		}
		return result;
	}

	public static String getApplicationName(Context ctx, String pkg) {
		try {
			PackageManager pm = ctx.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(pkg, 0);
			CharSequence cs = pm.getApplicationLabel(pi.applicationInfo);
			return cs == null ? "application" : cs.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static int getVersionCode(Context context) {
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			if (pi != null) {
				return pi.versionCode;
			}
		} catch (NameNotFoundException ex) {
			ex.printStackTrace();
		}
		return 0;
	}

	public static Integer getVersionCode(Context context, String packageName) {
		if (context == null) {
			LogUtil.e("PackageUtils", "context is null");
			return null;
		}
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);
			if (pi != null) {
				return pi.versionCode;
			}
		} catch (NameNotFoundException ex) {
			// ignore it
		}
		return null;
	}

	public static String getTopAppPkg(Context context) {
		String topAppPkg = "";
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
			topAppPkg = getTopAppPkgBeforeLollipop(context);
		} else {
			topAppPkg = getTopAppPkgAfterLollipop(context);
		}
		return topAppPkg;
	}

	@SuppressWarnings("deprecation")
	public static String getTopAppPkgBeforeLollipop(Context context) {
		ComponentName info = null;
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		try {
			info = activityManager.getRunningTasks(1).get(0).topActivity;
			return info.getPackageName();
		} catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String getTopAppPkgAfterLollipop(Context context) {
		final int START_TASK_TO_FRONT = 2;
		ActivityManager.RunningAppProcessInfo currentInfo = null;
		Field field = null;
		try {
			field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
			ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			List<ActivityManager.RunningAppProcessInfo> appList = am.getRunningAppProcesses();
			for (ActivityManager.RunningAppProcessInfo app : appList) {
				if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
					Integer state = field.getInt(app);
					if (state != null && state == START_TASK_TO_FRONT) {
						currentInfo = app;
						break;
					}
				}
			}
			if (currentInfo != null) {
				String[] pkgList = currentInfo.pkgList;
				if (pkgList != null && pkgList.length > 0) {
					return pkgList[0];
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

}
